/// <reference path="../Build/CesiumUnminified/Cesium.d.ts"/>

// 实现websocket通信

var ws = new WebSocket('ws://127.0.0.1:19910');

var flight_list = new HashTable()

ws.onopen = function(evt) {
  console.log('Connection open ...');
  ws.send('hello');
};

ws.onmessage = function(evt) {
  var raw = JSON.parse(evt.data);
  if(raw.data.length > 0){
    for(var i=0; i < raw.data.length; i++){
      var msg = flight_list.get(raw.data[i][0]);
      if( msg == null){
        flight_list.put(raw.data[i][0], raw.data[i]);
        point_add(raw.data[i]); // 添加目标
      }
      else{
        flight_list.put(raw.data[i][0], raw.data[i]);
      }
    }
    
  }
  // console.log(raw.data.length, flight_list.size())
  // console.log('Received Message: ' + evt.data);
  // console.log(raw.timestamp, raw.head)
};

ws.onclose = function(evt) {
  console.log('Connection closed.');
};

// 目标更新
const viewer = new Cesium.Viewer("cesiumContainer");

var lat = 37.0;
var lon = 121.0;

var point_options = {
  show: true, //是否展示
  pixelSize: 10, //点的大小
  color: Cesium.Color.RED.withAlpha(0), //颜色
  outlineColor: Cesium.Color.YELLOW, //边框颜色
  outlineWidth: 2, //边框宽度
}

function pos_callback(icao){
  msg = flight_list.get(icao);
  //console.log(msg);
  var originPosition = Cesium.Cartesian3.fromDegrees(msg[1], msg[2], msg[3]);
  return originPosition;
}

function point_add(msg)
{
  var icao = msg[0];
  var lon = msg[1];
  var lat = msg[2];
  var alt = msg[3];
  var heading = msg[4];
  var point=new Cesium.Entity({
    id: icao,
    // position: Cesium.Cartesian3.fromDegrees(lon, lat, alt),
    position: new Cesium.CallbackProperty(function(){return pos_callback(icao)}, false),
    point: point_options
  })

  viewer.entities.add(point);

  // point._position = new Cesium.CallbackProperty(function(){pos_callback(icao)}, false);
  // console.log(icao, lon, lat, alt, heading);
}

// function pos_update(msg){

//   var point = viewer.entities.getById();

// }


 viewer.zoomTo(viewer.entities);
